package xu.zhi.qing.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.aspectj.weaver.ast.Var;

/**
 * 装饰者模式完美解决编码问题
 * @author Lenovo_pc
 *
 */
public class EncodingFilter implements Filter{


	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		HttpServletRequest myRequest=new MyHttpServletRequest((HttpServletRequest)request);
		chain.doFilter(myRequest, response);
		
	}
	
	
	public static class MyHttpServletRequest extends HttpServletRequestWrapper{
		
		private HttpServletRequest request;

		public MyHttpServletRequest(HttpServletRequest request) {
			super(request);
			this.request=request;
		}
		
		//增强getParameter方法，自动解码并编码为utf-8的字符串
		@Override
		public String getParameter(String name) {
			String value=request.getParameter(name);
			if(value==null){
				return null;
			}
			if (request.getMethod().equals("GET")) {
				try {
					value=new String(value.getBytes("iso-8859-1"), "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
			return value;
		}
		
		@Override
		public String[] getParameterValues(String name) {
			String[] values=request.getParameterValues(name);
			if (values==null||!request.getMethod().equals("GET")) {
				return values;
			}
			try {
				for(int i=0;i<values.length;i++){
					values[i]=new String(values[i].getBytes("iso-8859-1"), "utf-8");
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			
			return values;
		}
		
		@Override
		public Map<String, String[]> getParameterMap() {
			Map<String, String[]> map=request.getParameterMap();
			if(!request.getMethod().equals("GET")){
				return map;
			}
			Set<Entry<String, String[]>> entrySet = map.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				String[] value = entry.getValue();
				for(int i=0;i<value.length;i++){
					try {
						value[i]=new String(value[i].getBytes("iso-8859-1"), "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						throw new RuntimeException(e);
					}
				}
			}
			return map;
		}
		
	}

	
	
	
	
	
	
	
	
	
	
	
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	@Override
	public void destroy() {
		
	}
	
}
